package org.biubiu0002.baiblog.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.common.constants.CacheConstants;
import org.biubiu0002.baiblog.common.constants.Constants;
import org.biubiu0002.baiblog.common.exception.BaiBlogException;
import org.biubiu0002.baiblog.common.exception.BizCodeEnumException;
import org.biubiu0002.baiblog.common.utils.PageUtils;
import org.biubiu0002.baiblog.common.utils.Query;
import org.biubiu0002.baiblog.core.dao.CommentRecordDao;
import org.biubiu0002.baiblog.core.model.dto.TokenUserDto;
import org.biubiu0002.baiblog.core.model.entity.CommentRecordEntity;
import org.biubiu0002.baiblog.core.model.entity.ShareEntity;
import org.biubiu0002.baiblog.core.model.vo.req.CommentDeleteReqVo;
import org.biubiu0002.baiblog.core.service.CommentRecordService;
import org.biubiu0002.baiblog.core.service.RichTextService;
import org.biubiu0002.baiblog.core.service.ShareService;
import org.biubiu0002.baiblog.core.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("commentRecordService")
public class CommentRecordServiceImpl extends ServiceImpl<CommentRecordDao, CommentRecordEntity> implements CommentRecordService {

    @Resource
    private ShareService shareService;

    @Resource
    private RichTextService richTextService;

    @Resource
    private CommentRecordDao commentRecordDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public CommentRecordEntity getById(String commentId) {
        return this.getOne(new QueryWrapper<CommentRecordEntity>()
                .eq("resource_id", commentId)
                .eq("is_deleted", 0));
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CommentRecordEntity> page = this.page(
                new Query<CommentRecordEntity>().getPage(params),
                new QueryWrapper<CommentRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void delete(CommentDeleteReqVo commentDeleteReqVo) {
        TokenUserDto user = SecurityUtils.getUser();
        if (user == null) {
            throw new BaiBlogException(BizCodeEnumException.AUTHENTICATE_FAIL_EXCEPTION);
        }
        String shareId = commentDeleteReqVo.getShareId();
        String commentId = commentDeleteReqVo.getCommentId();
        ShareEntity shareEntity = shareService.getByShareId(shareId);
        if (shareEntity == null) {
            throw new BaiBlogException(BizCodeEnumException.SHARE_NOT_EXIST_EXCEPTION);
        }
        CommentRecordEntity commentRecordEntity = this.getById(commentId);
        if(commentRecordEntity==null){
            throw new BaiBlogException(BizCodeEnumException.COMMENT_NOT_EXIST_EXCEPTION);
        }
        //帖子主删评论
        if(StringUtils.equals(user.getUserUid(), shareEntity.getUserUid())){
            doDeleteComment(shareId, Collections.singletonList(commentId));
        }
        //发评论主
        else if (StringUtils.equals(user.getUserUid(), commentRecordEntity.getUserUid())) {
            doDeleteComment(shareId, Collections.singletonList(commentId));
        }
        else{
            throw new BaiBlogException(BizCodeEnumException.AUTHORIZE_FAIL_EXCEPTION,"你无权删除别人的评论");
        }


    }

    public void doDeleteComment(String shareId, List<String> commentIds) {
        if(CollectionUtils.isEmpty(commentIds)){
            throw new BaiBlogException(BizCodeEnumException.INNER_INPUT_EXCEPTION);
        }
        //1.删除评论
        commentRecordDao.deleteByIds(commentIds);
        //2.删除评论对应的文本
        richTextService.updateCommentTextStatus(commentIds, Constants.DELETED);
        //3.帖子评论数
        int count = countComments(commentIds.size(), commentIds);
        redisTemplate.opsForValue().increment(CacheConstants.getShareCommentCountKey(shareId),-count);

    }

    int countComments(int count,List<String> commentId){
        if(CollectionUtils.isEmpty(commentId)){
            return count;
        }
        List<CommentRecordEntity> commentRecordEntities = commentRecordDao.selectByCommentedId(commentId);
        List<String> childrenIds = commentRecordEntities.stream().map(CommentRecordEntity::getResourceId).collect(Collectors.toList());
        return countComments(count+childrenIds.size(),childrenIds);

    }


}